package com.adcc.loadsheet.billing.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.chargerule.BillingLadderEntity;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.security.UserInfo;
import com.adcc.loadsheet.billing.service.BillingLadderService;
import com.adcc.loadsheet.billing.service.ChargeBillService;
import com.adcc.loadsheet.billing.service.ChargeDetailService;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.vo.ResultStatus;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.adcc.loadsheet.billing.vo.ScUpDataEntityVO;
import com.adcc.loadsheet.billing.vo.chargedetail.ChargeDetailVO;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 收费明细管理Controller层
 * Created by zhaoml on 2020/4/30.
 */
@Controller
@RequestMapping(value = "chargedetail")
@Api(value = "/chargedetail", description = "收费明细相关操作controller")
public class ChargeDetailController extends BasisController{

    @Autowired
    ContractUserService contractUserService;

    @Autowired
    ChargeDetailService chargeDetailService;

    @Autowired
    BillingLadderService billingLadderService;

    @Autowired
    ChargeBillService chargeBillService;

    //进入收费账单查询页面
    @PreAuthorize("hasPermission('','ChargeDetailQuery')")
    @GetMapping(value = "tochargedetailquery")
    @ApiOperation(value = "/tochargedetailquery", notes = "跳转到收费明细查询页面", httpMethod = "GET")
    public String toChargeDetailQuery(Model model) {
        //将合同用户列表传到页面，用以选择
        // 合同用户关联的普通用户（并授权此功能菜单）可以查询当前合同的用户的舱单计费统计账单，管理员可以查询全部合同用户的计费统计账单
        Map<String, Object> map = Maps.newHashMap();
        UserInfo userInfo = userContext.getCurrentUser();
        if(!userInfo.isSuperAdmin()){
            map.put("PB_LOGIN_ID",userInfo.getUsername());
        }
        List<ContractUserEntity> contractUserList = contractUserService.select(map);
        model.addAttribute("contractUserList", contractUserList);
        return "chargeDetail/chargedetail-query";
    }


    //查询收费明细
    @PostMapping(value = "findChargeDetail", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/findChargeDetail", notes = "查询收费明细", httpMethod = "POST")
    @ResponseBody
    public ResultVO findChargeDetail(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            Integer contractUserId = Integer.valueOf( map.get("contractUserId").toString());

            //通过合同用户查计费阶梯
            ContractUserEntity contractUserEntity = contractUserService.selectByPrimaryKey(contractUserId);
            List<BillingLadderEntity> billingLadderEntityList = billingLadderService.findByBillingRuleId(contractUserEntity.getBillingRuleId());
            //“本合同用户未指定计费阶梯，无法计价！”，不再生成帐单；
            if((billingLadderEntityList == null || billingLadderEntityList.size() == 0)){
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason("本合同用户未指定计费规则，无法计价！");
                return vo;
            }
//            ChargeBillVO chargeBillVO = chargeBillService.getChargeBill(startDate,endDate,contractUserEntity,billingLadderEntityList);
//            //“日均舱单数超出当前用户计费阶梯范围，无法计价！”，不再生成帐单；
//            BillingLadderEntity lastLadderEntity = billingLadderEntityList.get(billingLadderEntityList.size() - 1);
//            if(chargeBillVO.getAverage() > lastLadderEntity.getLadderEndnumber()){
//                vo.setStatus(ResultStatus.FAILED);
//                vo.setErrorReason("日均舱单数超出当前用户计费阶梯范围，无法计价！");
//                return vo;
//            }

            List<ChargeDetailVO> chargeDetailVOS = chargeDetailService.getChargeDetails(startDate,endDate,contractUserId);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("chargeDetails", chargeDetailVOS);
        } catch (Exception ex) {
            Log.error(ChargeDetailController.class, "查询收费明细出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query findChargeDetail", ex.fillInStackTrace()));
        }
        return vo;
    }

    //下载word格式
    @RequestMapping(value = "/word")
    @ResponseBody
    public String word(String startDate,String endDate,Integer contractUserId,HttpServletResponse response){
        try{
            String result = chargeDetailService.word(startDate, endDate, contractUserId, response);
            return result;
        }catch (Exception ex) {
            LogUtil.errorLog(ChargeDetailController.class, ex, "word()");
            return "";
        }
    }

    //下载pdf格式
    @RequestMapping(value = "/pdf", method = RequestMethod.GET)
    @ApiOperation(value = "/pdf", notes = "下载pdf格式", httpMethod = "GET")
    public @ResponseBody
    String pdf(String startDate,String endDate,Integer contractUserId,HttpServletResponse response){
        try{
            String result = chargeDetailService.pdf(startDate, endDate, contractUserId, response);
            return result;
        }catch (Exception ex) {
            LogUtil.errorLog(ChargeDetailController.class, ex, "pdf()");
            return "";
        }
    }

    //查询明细
    @PostMapping(value = "findDetails", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/findDetails", notes = "查询明细", httpMethod = "POST")
    @ResponseBody
    public ResultVO findDetails(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            String startDate = map.get("startDate").toString();
            String endDate = map.get("endDate").toString();
            Integer contractUserId = Integer.valueOf( map.get("contractUserId").toString());

            //通过合同用户查计费阶梯
            List<ScUpDataEntityVO> scUpDataEntityVOList = chargeDetailService.getDetails(startDate,endDate,contractUserId);

            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("scUpDataEntityVOList", scUpDataEntityVOList);
        } catch (Exception ex) {
            Log.error(ChargeDetailController.class, "查询明细出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query findDetails", ex.fillInStackTrace()));
        }
        return vo;
    }

    //导出明细excel
    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    @ApiOperation(value = "/excel", notes = "导出明细excel", httpMethod = "GET")
    public @ResponseBody
    void excel(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) {
        chargeDetailService.excel(startDate,endDate,contractUserId,response);
    }

    //打印
    @RequestMapping(value = "/print", method = RequestMethod.GET)
    @ApiOperation(value = "/print", notes = "打印", httpMethod = "GET")
    public @ResponseBody
    void print(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) {
        try{
            chargeDetailService.print(startDate,endDate,contractUserId,response);
        }catch (Exception ex) {
            LogUtil.errorLog(ChargeDetailController.class, ex, "print()");
        }
    }

    //打印明细excel
    @RequestMapping(value = "/printdetails", method = RequestMethod.GET)
    @ApiOperation(value = "/printdetails", notes = "打印明细excel", httpMethod = "GET")
    public @ResponseBody
    void printDetails(String startDate,String endDate,Integer contractUserId,HttpServletResponse response) throws Exception{
        try {
            chargeDetailService.printDetails(startDate,endDate,contractUserId,response);
        }catch (Exception ex){
            LogUtil.errorLog(ChargeDetailController.class, ex, "printDetails()");
        }
    }
}